import { ref, Ref, inject, nextTick, watch } from 'vue'
import { useStore } from 'vuex'
import { getSongDetailById, getLyric } from '@/apis/index'
import { formatTimeStamp } from '@/utils/utils'

interface AudioInfo extends Record<string, any> {
  url: string;
  picUrl: string;
  duration: SVGAnimatedNumberList;
  title: string;
  auth: string;
}

//播放器控制
export function useAudioControl() {
  const { state, commit } = useStore()
  const curentTime: Ref<string> = ref(state.currentTime)
  const isPlay: Ref<boolean> = ref(state.isPlay)
  const myAudio: Ref<HTMLAudioElement | null> | undefined = inject('myAudio')

  function timeupdate(callback?) {
    nextTick(() => {
      const audio = myAudio as Ref<HTMLAudioElement>
      audio.value.addEventListener('timeupdate', (e) => {
        curentTime.value = formatTimeStamp(audio.value.currentTime * 1000)
        commit('setCurrentTime', curentTime.value)
        callback && callback(e, audio.value)
      })
    })
  }
  function audioPlay(callback?) {
    nextTick(() => {
      myAudio?.value?.addEventListener('play', (e) => {
        isPlay.value = true
        commit("setIsPlay", isPlay);
        callback && callback(e, myAudio.value)
      })
    })
  }

  function audioEnd(callback?) {
    nextTick(() => {
      myAudio?.value?.addEventListener('ended', (e) => {
        isPlay.value = false
        commit("setIsPlay", isPlay);
        callback && callback(e, myAudio.value)
      })
    })
  }

  function togglePlay() {
    if (myAudio) {
      if (isPlay.value) {
        myAudio.value?.pause()
      } else {
        myAudio.value?.play()
      }
      isPlay.value = !isPlay.value
      commit('setIsPlay', isPlay)
    }
  }

  return {
    timeupdate,
    audioPlay,
    audioEnd,
    togglePlay,
    curentTime,
    myAudio,
    isPlay,

  }
}

//歌词相关逻辑
export function useAudioLyric(res) {
  const lyric = ref([])
  const waitPlayLyric = ref([])
  const hasPlayLyric = ref([])
  const lr = res.lrc.lyric.split('\n')
  lyric.value = lr.reduce((total, cur) => {
    if (!cur.startsWith('[')) {
      total.push(['', cur])
    } else {
      const l = cur.replace('[', '').split(']')
      l[0] = l[0].split('.')[0]
      total.push(l)
    }
    return total.filter(t => t[1])
  }, [])
  waitPlayLyric.value = lyric.value
  function changeLyric(tim) {
    let index = 0
    lyric.value.forEach((item, i) => {
      if (item[0] === tim) {
        index = i
      }
    })
    if (index > 0) {
      hasPlayLyric.value = lyric.value.slice(0, index + 1)
      waitPlayLyric.value = lyric.value.slice(index + 1)
    }
  }
  return {
    lyric,
    waitPlayLyric,
    hasPlayLyric,
    changeLyric
  }
}


//获取音乐详情
export async function useAudioDetail(id) {
  const { commit, state } = useStore()
  const audioInfo: Ref<AudioInfo | null> = ref(null)
  const { myAudio, curentTime, isPlay, timeupdate, audioPlay, audioEnd, togglePlay } = useAudioControl()

  const res = await Promise.all([getSongDetailById(id), getLyric(id)])
  const song = res[0].songs[0]
  const { hasPlayLyric, waitPlayLyric, changeLyric } = useAudioLyric(res[1])

  audioInfo.value = {
    url: `https://music.163.com/song/media/outer/url?id=${id}.mp3`,
    picUrl: song.al.picUrl,
    duration: song.dt,
    title: song.name,
    auth: song.ar.map(i => i.name).join('、'),
    waitPlayLyric,
    hasPlayLyric,
  }
  commit('setCurrentAudio', audioInfo.value)
  changeLyric(curentTime.value)

  watch(() => state.currentTime, (nval) => {
    changeLyric(nval)
  })
  //音频及进度变化事件
  timeupdate()
  //音频播放事件
  audioPlay()
  //音频播放结束
  audioEnd()

  return {
    audioInfo,
    myAudio,
    isPlay,
    curentTime,
    togglePlay
  }
}



